#!/usr/bin/env bash
#
#  Copyright (c) 2021, The OpenThread Authors.
#  All rights reserved.
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are met:
#  1. Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
#  2. Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#  3. Neither the name of the copyright holder nor the
#     names of its contributors may be used to endorse or promote products
#     derived from this software without specific prior written permission.
#
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
#  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
#  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
#  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
#  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
#  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
#  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
#  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
#  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
#  POSSIBILITY OF SUCH DAMAGE.
#

set -euxo pipefail

# ==============================================================================
# Bash definitions

if [[ -n ${BASH_SOURCE[0]} ]]; then
    script_path="${BASH_SOURCE[0]}"
else
    script_path="$0"
fi
script_dir="$(realpath "$(dirname "${script_path}")")"
repo_dir="$(dirname "${script_dir}")"

# ==============================================================================
install_packages_apt()
{
    echo 'Installing script dependencies...'

    # Install dependencies
    sudo apt-get update
    apt_packages=(
        ccache
        coreutils
        git
        git-lfs
        openjdk-17-jre-headless
        ninja-build
        python3-pip
        python3-setuptools
        unzip
        wget
        xz-utils
    )
    sudo apt-get --no-install-recommends install -y "${apt_packages[@]}"
}

install_packages_opkg()
{
    echo 'opkg not supported currently' && false
}

install_packages_rpm()
{
    echo 'rpm not supported currently' && false
}

install_packages_brew()
{
    echo 'Installing script dependencies...'

    brew_packages=(
        ccache
        coreutils
        git
        git-lfs
        grep
        ninja
        openjdk@17
        unzip
        wget
    )
    brew install "${brew_packages[@]}"
}

install_packages_source()
{
    echo 'source not supported currently' && false
}

install_packages_pip3()
{
    pip3 install --no-cache-dir --upgrade -r "${repo_dir}/requirements.txt"
}

install_packages()
{
    PM=source
    if command -v apt-get; then
        PM=apt
    elif command -v rpm; then
        PM=rpm
    elif command -v opkg; then
        PM=opkg
    elif command -v brew; then
        PM=brew
    fi
    install_packages_$PM
}

do_bootstrap_silabs()
{
    echo "Bootstrapping silabs"
    "${repo_dir}"/script/bootstrap_silabs
}

install_arm_toolchain()
{
    local url=${1-"https://developer.arm.com/-/media/Files/downloads/gnu/12.2.rel1/binrel/arm-gnu-toolchain-12.2.rel1-x86_64-arm-none-eabi.tar.xz"}
    local extract_dir=${2-"arm-gnu-toolchain-12.2.rel1-x86_64-arm-none-eabi"}
    local toolchain_dir=${3-""}

    # If toolchain_dir is not provided, use /opt if root, else use ~/.local
    if [ -z "${toolchain_dir}" ]; then
        if [ "$EUID" -eq 0 ]; then
            toolchain_dir=/opt
        else
            toolchain_dir="${HOME}/.local"
        fi
    fi

    # Check if the toolchain is already present at the desired location
    if command -v "${toolchain_dir}/${extract_dir}/bin/arm-none-eabi-gcc"; then
        echo "'arm-none-eabi-gcc' found. Skipping GNU ARM Embedded toolchain install"
        "${toolchain_dir}"/"${extract_dir}"/bin/arm-none-eabi-gcc --version
        return
    fi

    echo 'Installing GNU ARM Embedded Toolchain...'

    # Download
    local tarball=gcc-arm.tar.xz
    mkdir -p "${toolchain_dir}/${extract_dir}"
    wget --tries 4 --no-check-certificate --quiet "${url}" -O "${toolchain_dir}/${tarball}"

    # Extract
    tar xf "${toolchain_dir}/${tarball}" --directory "${toolchain_dir}/${extract_dir}" --strip-components=1

    # Link if root
    if [ "$EUID" -eq 0 ]; then
        ln -s -f "${toolchain_dir}"/"${extract_dir}"/bin/* /usr/local/bin/
        ls -alh /usr/local/bin/arm*
    else
        set +x
        echo ""
        echo "The bootstrap script was run without sudo"
        echo ""
        echo "Make sure to add '${toolchain_dir}/${extract_dir}/bin/' to PATH"
        echo ""
        set -x
    fi

    # Cleanup
    rm -rf "${toolchain_dir:?}/${tarball:?}"
}

main()
{
    if [ $# == 0 ]; then
        install_packages
        install_arm_toolchain
        install_packages_pip3
        do_bootstrap_silabs
    elif [ "$1" == 'packages' ]; then
        install_packages
    elif [ "$1" == 'arm_toolchain' ]; then
        shift 1
        install_arm_toolchain "$@"
    elif [ "$1" == 'python' ]; then
        install_packages_pip3
    elif [ "$1" == 'silabs' ]; then
        do_bootstrap_silabs
    else
        echo >&2 "Unsupported action: $1. Supported: packages, arm_toolchain, python, silabs"
        # 128 for Invalid arguments
        exit 128
    fi

    echo "Bootstrap completed successfully."
}

main "$@"
